// 全局变量
let editingSavingsId = null;
let deletingSavingsId = null;

// 初始化页面
function initPage() {
    // 初始化储蓄管理器
    const savingsManager = new window.AppData.SavingsManager();
    
    // 刷新储蓄目标列表
    refreshSavingsList();
    
    // 更新储蓄概览
    updateSavingsSummary();
}

// 刷新储蓄目标列表
function refreshSavingsList() {
    const savingsManager = new window.AppData.SavingsManager();
    const savingsProgress = savingsManager.getCurrentSavingsProgress();
    
    const savingsListElement = document.getElementById('savingsList');
    const emptyStateElement = document.getElementById('emptyState');
    
    // 没有储蓄目标时显示空状态
    if (savingsProgress.length === 0) {
        savingsListElement.style.display = 'none';
        emptyStateElement.style.display = 'block';
        return;
    }
    
    // 有储蓄目标时隐藏空状态
    savingsListElement.style.display = 'block';
    emptyStateElement.style.display = 'none';
    
    // 构建HTML
    let html = '';
    
    savingsProgress.forEach(goal => {
        // 确定进度条颜色
        let progressClass = 'progress-normal';
        if (goal.percentage >= 50 && goal.percentage < 100) {
            progressClass = 'progress-halfway';
        } else if (goal.percentage >= 100) {
            progressClass = 'progress-complete';
        }
        
        html += `
            <div class="savings-item">
                <div class="savings-header">
                    <div class="savings-goal">
                        <div class="goal-icon">
                            <i class="material-icons">savings</i>
                        </div>
                        <div class="goal-name">${goal.name || '储蓄目标'}</div>
                    </div>
                    <div class="savings-actions">
                        <div class="savings-edit" onclick="editSavingsGoal('${goal.id}')">
                            <i class="material-icons">edit</i>
                        </div>
                        <div class="savings-delete" onclick="deleteSavingsGoal('${goal.id}')">
                            <i class="material-icons">delete</i>
                        </div>
                    </div>
                </div>
                <div class="savings-details">
                    <div class="savings-amount">
                        <div class="amount-label">目标金额</div>
                        <div class="amount-value">¥${goal.targetAmount.toFixed(2)}</div>
                    </div>
                    <div class="savings-amount">
                        <div class="amount-label">已储蓄</div>
                        <div class="amount-value">¥${goal.savedAmount.toFixed(2)}</div>
                    </div>
                    <div class="savings-amount">
                        <div class="amount-label">剩余</div>
                        <div class="amount-value">¥${goal.remaining.toFixed(2)}</div>
                    </div>
                    <div class="savings-amount">
                        <div class="amount-label">储蓄率</div>
                        <div class="amount-value">${goal.savingRate}%</div>
                    </div>
                    <div class="savings-progress">
                        <div class="progress-bar ${progressClass}" style="width: ${goal.percentage}%"></div>
                    </div>
                </div>
            </div>
        `;
    });
    
    savingsListElement.innerHTML = html;
}

// 更新储蓄概览
function updateSavingsSummary() {
    const savingsManager = new window.AppData.SavingsManager();
    const savingsProgress = savingsManager.getCurrentSavingsProgress();
    const transactionManager = new window.AppData.TransactionManager();
    const transactions = transactionManager.getTransactions();
    
    // 计算总收入
    let totalIncome = 0;
    transactions.filter(t => t.type === 'income').forEach(t => {
        totalIncome += t.amount;
    });
    
    // 计算总储蓄金额
    let totalSaved = 0;
    savingsProgress.forEach(goal => {
        totalSaved += goal.savedAmount;
    });
    
    // 计算整体储蓄率
    const overallSavingRate = totalIncome > 0 ? (totalSaved / totalIncome) * 100 : 0;
    
    // 更新UI
    document.querySelector('#totalIncome .summary-value').textContent = `¥${totalIncome.toFixed(2)}`;
    document.querySelector('#totalSaved .summary-value').textContent = `¥${totalSaved.toFixed(2)}`;
    document.querySelector('#savingRate .summary-value').textContent = `${overallSavingRate.toFixed(1)}%`;
}

// 打开添加储蓄目标模态框
function openAddSavingsModal() {
    document.getElementById('modalTitle').textContent = '添加储蓄目标';
    document.getElementById('savingsNameInput').value = '';
    document.getElementById('targetAmountInput').value = '';
    document.getElementById('savingRateInput').value = '';
    editingSavingsId = null;
    
    // 显示模态框
    document.getElementById('savingsModal').style.display = 'flex';
}

// 打开编辑储蓄目标模态框
function editSavingsGoal(savingsId) {
    const savingsManager = new window.AppData.SavingsManager();
    const savingsGoals = savingsManager.getSavingsGoals();
    
    const goal = savingsGoals.find(g => g.id === savingsId);
    if (!goal) return;
    
    document.getElementById('modalTitle').textContent = '编辑储蓄目标';
    document.getElementById('savingsNameInput').value = goal.name || '';
    document.getElementById('targetAmountInput').value = goal.targetAmount;
    document.getElementById('savingRateInput').value = goal.savingRate;
    editingSavingsId = savingsId;
    
    // 显示模态框
    document.getElementById('savingsModal').style.display = 'flex';
}

// 关闭模态框
function closeModal() {
    document.getElementById('savingsModal').style.display = 'none';
}

// 保存储蓄目标
function saveSavingsGoal() {
    const name = document.getElementById('savingsNameInput').value.trim();
    const targetAmountInput = document.getElementById('targetAmountInput').value.trim();
    const savingRateInput = document.getElementById('savingRateInput').value.trim();
    
    // 验证
    if (!name) {
        showToast('请输入目标名称', true);
        return;
    }
    
    if (!targetAmountInput || isNaN(targetAmountInput) || parseFloat(targetAmountInput) <= 0) {
        showToast('请输入有效的目标金额', true);
        return;
    }
    
    if (!savingRateInput || isNaN(savingRateInput) || parseFloat(savingRateInput) <= 0 || parseFloat(savingRateInput) > 100) {
        showToast('请输入有效的储蓄率 (1-100)', true);
        return;
    }
    
    const targetAmount = parseFloat(targetAmountInput);
    const savingRate = parseFloat(savingRateInput);
    
    // 初始化储蓄管理器
    const savingsManager = new window.AppData.SavingsManager();
    
    if (editingSavingsId) {
        // 编辑现有储蓄目标
        const savingsGoals = savingsManager.getSavingsGoals();
        const index = savingsGoals.findIndex(g => g.id === editingSavingsId);
        
        if (index !== -1) {
            const updatedGoal = {
                ...savingsGoals[index],
                name: name,
                targetAmount: targetAmount,
                savingRate: savingRate
            };
            
            savingsManager.updateSavingsGoal(updatedGoal);
        }
    } else {
        // 添加新储蓄目标
        const newGoal = {
            name: name,
            targetAmount: targetAmount,
            savingRate: savingRate
        };
        
        savingsManager.addSavingsGoal(newGoal);
    }
    
    // 关闭模态框
    closeModal();
    
    // 刷新储蓄目标列表
    refreshSavingsList();
    
    // 更新储蓄概览
    updateSavingsSummary();
    
    // 显示成功提示
    showToast(editingSavingsId ? '储蓄目标已更新' : '储蓄目标已添加');
}

// 删除储蓄目标
function deleteSavingsGoal(savingsId) {
    deletingSavingsId = savingsId;
    document.getElementById('deleteModal').style.display = 'flex';
}

// 关闭删除模态框
function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
    deletingSavingsId = null;
}

// 确认删除储蓄目标
function confirmDeleteSavingsGoal() {
    if (!deletingSavingsId) return;
    
    // 初始化储蓄管理器
    const savingsManager = new window.AppData.SavingsManager();
    
    // 删除储蓄目标
    const success = savingsManager.deleteSavingsGoal(deletingSavingsId);
    
    if (success) {
        // 关闭模态框
        closeDeleteModal();
        
        // 刷新储蓄目标列表
        refreshSavingsList();
        
        // 更新储蓄概览
        updateSavingsSummary();
        
        // 显示成功提示
        showToast('储蓄目标已删除');
    } else {
        showToast('删除储蓄目标失败', true);
    }
}

// 显示提示
function showToast(message, isError = false) {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.classList.add('show');
    
    if (isError) {
        toast.classList.add('error');
    } else {
        toast.classList.remove('error');
    }
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage); 